package battlezone;

import java.net.*;

public class Server extends Thread {
    private static Configuration _configuration = Configuration.getInstance();
    private DatagramSocket _socket;
    private Model _model;
    private byte[] _packetPayload = new byte[256]; //TODO: figure out what the most appropriate size for the array is
    private DatagramPacket _packet = new DatagramPacket(_packetPayload, 256);
    
    public Server(Model model) throws SocketException {
        _model = model;
        _socket = new DatagramSocket(_configuration.getPortNumber());
    }

    @Override
    public void run() {
        while (true) {
            try {
                _socket.receive(_packet);
                String command = new String(_packetPayload, 0, _packet.getLength());
                System.out.println(command);
                
                String[] parameters = command.split(" ");
                if (parameters[0].equals("ENTER")) {
                    _model.addPlayer();
                } else if (parameters[0].equals("ADD")) {
                    if (parameters[2].equals("tank-live")) {
                        _model.addObject(parameters[1], new Tank(0, 0, 0));
                    } else {
                        _model.addObject(parameters[1], new Projectile(0, 0, 0), parameters[3].equals("fire"));
                    }
                } else if (parameters[0].equals("REMOVE")) {
                    _model.removeObject(parameters[1]);
                } else if (parameters[0].equals("UPDATE")) {
                    _model.updateObjectPosition(parameters[1], Float.parseFloat(parameters[2]), Float.parseFloat(parameters[3]), Float.parseFloat(parameters[4]));
                } else if (parameters[0].equals("KILL")) {
                    _model.killObject(parameters[1]);
                } //LEAVE command is not used
            } catch (Exception ex) {
                System.err.println(ex.getMessage());
            }
        }
    }
}

